<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>在线会议系统</title>
</head>
<body>
	<h2>欢迎使用会议系统</h2>
	会议邀请码：
	<input id="randStr" type="text" />
	<button id="open" onclick="openWebsocket()">加入会议</button>
	<hr />
	消息内容：
	<input id="text" type="text" />
	<button id="send" disabled="disabled" onclick="send()">发送消息</button>
	<hr />
	<button id="close" disabled="disabled" onclick="closeWebSocket()">离开会议</button>
	<hr />
	<div id="message"></div>
</body>

<script type="text/javascript">
	var websocket = null;
	var remote = window.location.host;
	function openWebsocket() {
		var randStr = document.getElementById('randStr').value;
		//判断当前浏览器是否支持WebSocket
		if ('WebSocket' in window) {
			websocket = new WebSocket("ws://" + window.location.host
					+ "/websocket/tomcat/meeting?randStr=" + randStr);

			//连接发生错误的回调方法
			websocket.onerror = function() {
				setMessageInnerHTML("会议连接发生错误!");
			};

			//连接成功建立的回调方法
			websocket.onopen = function() {
				setMessageInnerHTML("会议连接成功...");
				document.getElementById("open").disabled = true;
				document.getElementById("randStr").disabled = true;
				document.getElementById("send").disabled = false;
				document.getElementById("close").disabled = false;
			}

			//接收到消息的回调方法
			websocket.onmessage = function(event) {
				setMessageInnerHTML(event.data);
			}

			//连接关闭的回调方法
			websocket.onclose = function() {
				setMessageInnerHTML("会议结束，连接关闭!");
				document.getElementById("randStr").disabled = false;
				document.getElementById("open").disabled = false;
				document.getElementById("send").disabled = true;
				document.getElementById("close").disabled = true;
			}

			//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常
			window.onbeforeunload = function() {
				closeWebSocket();
			}
		} else {
			alert('当前浏览器 Not support websocket');
		}
	}

	//将消息显示在网页上
	function setMessageInnerHTML(innerHTML) {
		document.getElementById('message').innerHTML += innerHTML + '<br/>';
	}

	//关闭WebSocket连接
	function closeWebSocket() {
		websocket.close();
	}

	//发送消息
	function send() {
		var content = document.getElementById('text').value;
		websocket.send(content);
	}
</script>
</html>